const appKey = process.env.APP_KEY;
import Vue from "vue";
import App from "./App.vue";
import routes from "@/router/index";
import store from "@/store/index";
import Nprogress from "nprogress";
import "nprogress/nprogress.css";
import MicroApp from "./microApp/index";
import { microAppRouter } from "./microApp/router";
import { microAppStore } from "./microApp/store";
import VueRouter from "vue-router";
import i18n from "./utils/i18n";
Vue.use(VueRouter);

Vue.config.productionTip = false;

let router = null;
let instance = null;
function render(props) {
  const { container } = props || { container: null };
  const options = {
    install(app, next) {
      app.createRouter(microAppRouter.routes);
      app.createStore(microAppStore.state);
      //app.setDefaultMountApp("/app-vue");
      app.start();
      next();
    },
  };

  new MicroApp(
    !container
      ? options
      : {
          install(app, next) {
            next();
          },
        }
  )
    .then(() => {
      router = new VueRouter({
        routes,
      });

      router.beforeEach((to, from, next) => {
        console.log("[beforeEach]", to, from);
        Nprogress.start();
        if (
          container &&
          window.__POWERED_BY_QIANKUN__ &&
          !to.path.includes(appKey)
        ) {
          next({
            path: appKey + to.path,
          });
        } else {
          next();
        }
      });

      router.afterEach((to, from) => {
        console.log("[afterEach]", to, from);
        Nprogress.done();
      });

      instance = new Vue({
        i18n,
        router,
        store,
        render: (h) => h(App),
      }).$mount(container ? container.querySelector("#app") : "#app");
    })
    .catch((err) => {
      console.error(err);
    });
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

export async function bootstrap() {
  console.log("[vue] vue app bootstraped");
}
export async function mount(props) {
  console.log("[vue] props from main framework", props);
  // 注册应用间通信  props是基座传输过来的值，可进行token等存储使用
  // appStore(props)// 存储例子1 可作参考
  Vue.prototype.$MicroMount = props;

  // 设置应用间通讯（以下两行代码）
  Vue.prototype.$onGlobalStateChange = props.onGlobalStateChange;
  Vue.prototype.$setGlobalState = props.setGlobalState;

  // Cookies.set(props,'$MicroMount')
  // 注册微应用实例化函数
  render(props);
}
export async function unmount() {
  instance.$destroy();
  instance.$el.innerHTML = "";
  instance = null;
  router = null;
}
